<template>
  <div class="records-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">
            <el-icon class="title-icon"><Document /></el-icon>
            考试记录
          </h1>
          <p class="page-subtitle">查看您的考试历史和成绩详情</p>
        </div>
        <div class="header-stats">
          <div class="stat-card">
            <div class="stat-value">{{ totalExams }}</div>
            <div class="stat-label">总考试数</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ completedExams }}</div>
            <div class="stat-label">已完成</div>
          </div>
          <div class="stat-card">
            <div class="stat-value">{{ averageScore }}%</div>
            <div class="stat-label">平均分</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-content">
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="搜索考试名称..."
            prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </div>
        <div class="filter-controls">
          <el-select v-model="statusFilter" placeholder="考试状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="已完成" value="completed" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="未开始" value="pending" />
          </el-select>
          <el-select v-model="subjectFilter" placeholder="科目" clearable>
            <el-option label="全部" value="" />
            <el-option label="数学" value="math" />
            <el-option label="英语" value="english" />
            <el-option label="计算机" value="computer" />
          </el-select>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </div>
      </div>
    </div>

    <!-- 考试记录列表 -->
    <div class="records-content">
      <div class="records-list">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        <div v-else-if="filteredRecords.length === 0" class="empty-state">
          <el-empty description="暂无考试记录" />
        </div>
        <div v-else class="record-cards">
          <div
            v-for="record in paginatedRecords"
            :key="record.id"
            class="record-card"
            @click="viewDetail(record)"
          >
            <div class="card-header">
              <div class="exam-info">
                <h3 class="exam-title">{{ record.examTitle }}</h3>
                <div class="exam-meta">
                  <span class="subject-tag">{{ record.subject }}</span>
                  <span class="exam-date">{{ formatDate(record.examDate) }}</span>
                </div>
              </div>
              <div class="exam-status">
                <el-tag
                  :type="getStatusType(record.status)"
                  :effect="record.status === 'completed' ? 'dark' : 'plain'"
                >
                  {{ getStatusText(record.status) }}
                </el-tag>
              </div>
            </div>
            <div class="card-content">
              <div class="score-section" v-if="record.status === 'completed'">
                <div class="score-display">
                  <div class="score-value">{{ record.score }}</div>
                  <div class="score-total">/ {{ record.totalScore }}</div>
                </div>
                <div class="score-percentage"
                     :class="getScoreClass(record.scorePercentage)">
                  {{ record.scorePercentage }}%
                </div>
              </div>
              <div class="exam-details">
                <div class="detail-item">
                  <el-icon><Clock /></el-icon>
                  <span>用时: {{ record.duration || '未完成' }}</span>
                </div>
                <div class="detail-item">
                  <el-icon><Document /></el-icon>
                  <span>题目: {{ record.totalQuestions }}题</span>
                </div>
                <div class="detail-item" v-if="record.status === 'completed'">
                  <el-icon><Check /></el-icon>
                  <span>正确: {{ record.correctAnswers }}题</span>
                </div>
              </div>
            </div>
            <div class="card-actions" v-if="record.status === 'completed'">
              <el-button size="small" @click.stop="viewAnswers(record)">
                <el-icon><View /></el-icon>
                查看答案
              </el-button>
              <el-button size="small" @click.stop="reviewMistakes(record)">
                <el-icon><Warning /></el-icon>
                错题回顾
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="filteredRecords.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="filteredRecords.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 考试详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="selectedRecord?.examTitle"
      width="80%"
      top="5vh"
    >
      <div v-if="selectedRecord" class="detail-content">
        <div class="detail-header">
          <div class="detail-stats">
            <div class="stat-item">
              <label>考试时间:</label>
              <span>{{ formatDateTime(selectedRecord.examDate) }}</span>
            </div>
            <div class="stat-item">
              <label>考试时长:</label>
              <span>{{ selectedRecord.timeLimit }}分钟</span>
            </div>
            <div class="stat-item">
              <label>实际用时:</label>
              <span>{{ selectedRecord.duration }}</span>
            </div>
            <div class="stat-item">
              <label>总分:</label>
              <span>{{ selectedRecord.totalScore }}分</span>
            </div>
            <div class="stat-item">
              <label>得分:</label>
              <span class="score-highlight">{{ selectedRecord.score }}分</span>
            </div>
            <div class="stat-item">
              <label>正确率:</label>
              <span :class="getScoreClass(selectedRecord.scorePercentage)">
                {{ selectedRecord.scorePercentage }}%
              </span>
            </div>
          </div>
        </div>
        <div class="detail-chart">
          <h4>答题分析</h4>
          <div ref="chartContainer" class="chart-container"></div>
        </div>
      </div>
    </el-dialog>

    <!-- 答案查看对话框 -->
    <el-dialog
      v-model="answersDialogVisible"
      title="考试答案"
      width="90%"
      top="5vh"
    >
      <div class="answers-content">
        <div
          v-for="(question, index) in selectedRecord?.questions"
          :key="index"
          class="question-item"
        >
          <div class="question-header">
            <span class="question-number">第{{ index + 1 }}题</span>
            <el-tag
              :type="question.isCorrect ? 'success' : 'danger'"
              size="small"
            >
              {{ question.isCorrect ? '正确' : '错误' }}
            </el-tag>
          </div>
          <div class="question-content">
            <p class="question-text">{{ question.content }}</p>
            <div class="answer-section">
              <div class="answer-item">
                <label>您的答案:</label>
                <span :class="question.isCorrect ? 'correct-answer' : 'wrong-answer'">
                  {{ question.userAnswer }}
                </span>
              </div>
              <div class="answer-item" v-if="!question.isCorrect">
                <label>正确答案:</label>
                <span class="correct-answer">{{ question.correctAnswer }}</span>
              </div>
              <div class="answer-item" v-if="question.explanation">
                <label>解析:</label>
                <span class="explanation">{{ question.explanation }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Clock, Check, View, Warning, Search } from '@element-plus/icons-vue'
import { getStudentExam } from '@/api/exam/exams'
import { getExamSessionByExamAndStudent } from '@/api/exam/examSessions'
import * as echarts from 'echarts'
import { getMyGrades } from '@/api/student/grades'

// 响应式数据
const loading = ref(false)
const records = ref([])
const searchQuery = ref('')
const statusFilter = ref('')
const subjectFilter = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const detailDialogVisible = ref(false)
const answersDialogVisible = ref(false)
const selectedRecord = ref(null)
const chartContainer = ref(null)

// 计算属性
const totalExams = computed(() => records.value.length)
const completedExams = computed(() => 
  records.value.filter(r => r.status === 'completed').length
)
const averageScore = computed(() => {
  const completed = records.value.filter(r => r.status === 'completed')
  if (completed.length === 0) return 0
  const total = completed.reduce((sum, r) => sum + r.scorePercentage, 0)
  return Math.round(total / completed.length)
})

const filteredRecords = computed(() => {
  let filtered = records.value
  
  // 搜索过滤
  if (searchQuery.value) {
    filtered = filtered.filter(record => 
      record.examTitle.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  
  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(record => record.status === statusFilter.value)
  }
  
  // 科目过滤
  if (subjectFilter.value) {
    filtered = filtered.filter(record => record.subject === subjectFilter.value)
  }
  
  // 日期过滤
  if (dateRange.value && dateRange.value.length === 2) {
    filtered = filtered.filter(record => {
      const examDate = new Date(record.examDate)
      const startDate = new Date(dateRange.value[0])
      const endDate = new Date(dateRange.value[1])
      return examDate >= startDate && examDate <= endDate
    })
  }
  
  return filtered.sort((a, b) => new Date(b.examDate) - new Date(a.examDate))
})

const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRecords.value.slice(start, end)
})

// 方法
const loadRecords = async () => {
  loading.value = true
  try {
    const response = await getMyGrades()
    if (response.code === 200) {
      // 转换API返回的成绩数据为页面需要的记录数据格式
      const transformedData = await Promise.all((response.data || []).map(async grade => {
        // 计算分数和正确率
        const score = grade.score || 0
        const totalScore = grade.totalScore || 100
        const scorePercentage = totalScore > 0 ? Math.round((score / totalScore) * 100) : 0
        
        // 获取考试名称，根据examId调用接口获取正确的考试标题
        let examName = `考试 ${grade.examId}`
        let totalQuestions = Math.max(1, Math.floor(totalScore / 5)) // 默认根据总分估算
        let duration = '未知' // 默认时长
        
        if (grade.examId) {
          try {
            const examResponse = await getStudentExam(grade.examId)
            if (examResponse && examResponse.code === 200 && examResponse.data) {
              examName = examResponse.data.title || examName
              // 使用实际的题目数量
              if (examResponse.data.questions && Array.isArray(examResponse.data.questions)) {
                totalQuestions = examResponse.data.questions.length
              }
            }
            
            // 获取考试会话信息来计算时长
            try {
              const sessionResponse = await getExamSessionByExamAndStudent(grade.examId)
              if (sessionResponse && sessionResponse.code === 200 && sessionResponse.data) {
                const sessionData = sessionResponse.data
                if (sessionData.createdAt && sessionData.updatedAt) {
                  const startTime = new Date(sessionData.createdAt)
                  const endTime = new Date(sessionData.updatedAt)
                  const durationMs = endTime - startTime
                  const durationMinutes = Math.round(durationMs / (1000 * 60))
                  duration = `${durationMinutes}分钟`
                }
              }
            } catch (sessionError) {
              console.warn('获取考试会话信息失败:', sessionError)
            }
          } catch (examError) {
            console.warn('获取考试详情失败:', examError)
            examName = `考试 ${grade.examId}`
          }
        }
        
        return {
          id: grade.gradeId,
          examId: grade.examId,
          examTitle: examName,
          subject: '综合考试', // StudentGrade中没有科目信息
          examDate: grade.createdAt, // 使用成绩创建时间作为考试时间
          status: 'completed', // 有成绩记录说明考试已完成
          duration: duration, // 根据exam_sessions的created_at和updated_at计算
          timeLimit: 120, // 默认时长
          totalQuestions: totalQuestions, // 使用实际的题目数量
          correctAnswers: Math.floor((score / totalScore) * totalQuestions), // 根据得分率和实际题目数计算正确题数
          score: score,
          totalScore: totalScore,
          scorePercentage: scorePercentage,
          questions: [] // StudentGrade中没有具体题目信息
        }
      }))
      
      records.value = transformedData
    } else {
      ElMessage.error(response.message || '加载考试记录失败')
      records.value = []
    }
  } catch (error) {
    console.error('加载考试记录失败:', error)
    ElMessage.error('加载考试记录失败')
    records.value = []
  } finally {
    loading.value = false
  }
}

// 计算考试时长的辅助函数
const calculateDuration = (startTime, endTime) => {
  const start = new Date(startTime)
  const end = new Date(endTime)
  const diffMs = end - start
  const diffMins = Math.floor(diffMs / (1000 * 60))
  const hours = Math.floor(diffMins / 60)
  const mins = diffMins % 60
  
  if (hours > 0) {
    return `${hours}小时${mins}分钟`
  } else {
    return `${mins}分钟`
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleDateChange = () => {
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const viewDetail = (record) => {
  selectedRecord.value = record
  detailDialogVisible.value = true
  nextTick(() => {
    if (record.status === 'completed') {
      initChart()
    }
  })
}

const viewAnswers = (record) => {
  selectedRecord.value = record
  answersDialogVisible.value = true
}

const reviewMistakes = (record) => {
  // 跳转到错题回顾页面
  ElMessage.info('跳转到错题回顾页面')
}

const getStatusType = (status) => {
  const types = {
    completed: 'success',
    ongoing: 'warning',
    pending: 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    completed: '已完成',
    ongoing: '进行中',
    pending: '未开始'
  }
  return texts[status] || '未知'
}

const getScoreClass = (percentage) => {
  if (percentage >= 90) return 'excellent'
  if (percentage >= 80) return 'good'
  if (percentage >= 60) return 'pass'
  return 'fail'
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

const initChart = () => {
  if (!chartContainer.value) return
  
  const chart = echarts.init(chartContainer.value)
  const option = {
    title: {
      text: '答题正确率分析',
      left: 'center',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '答题情况',
        type: 'pie',
        radius: '50%',
        data: [
          { value: selectedRecord.value.correctAnswers, name: '正确' },
          { 
            value: selectedRecord.value.totalQuestions - selectedRecord.value.correctAnswers, 
            name: '错误' 
          }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 生命周期
onMounted(() => {
  loadRecords()
})
</script>

<style scoped>
.records-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.page-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
  margin: 0 0 8px 0;
}

.title-icon {
  margin-right: 12px;
  color: #165dff;
}

.page-subtitle {
  color: #86909c;
  margin: 0;
}

.header-stats {
  display: flex;
  gap: 24px;
}

.stat-card {
  text-align: center;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  min-width: 80px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #165dff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #86909c;
}

.filter-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.filter-content {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-box {
  flex: 1;
  min-width: 200px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.records-content {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.loading-container,
.empty-state {
  padding: 40px 0;
}

.record-cards {
  display: grid;
  gap: 16px;
}

.record-card {
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.record-card:hover {
  border-color: #165dff;
  box-shadow: 0 4px 12px rgba(22, 93, 255, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.exam-title {
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
  margin: 0 0 8px 0;
}

.exam-meta {
  display: flex;
  gap: 12px;
  align-items: center;
}

.subject-tag {
  background: #f2f3f5;
  color: #4e5969;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.exam-date {
  color: #86909c;
  font-size: 12px;
}

.card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.score-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.score-display {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.score-value {
  font-size: 24px;
  font-weight: 600;
  color: #165dff;
}

.score-total {
  color: #86909c;
  font-size: 14px;
}

.score-percentage {
  font-weight: 600;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.score-percentage.excellent {
  background: #f6ffed;
  color: #52c41a;
}

.score-percentage.good {
  background: #e6f7ff;
  color: #1890ff;
}

.score-percentage.pass {
  background: #fff7e6;
  color: #fa8c16;
}

.score-percentage.fail {
  background: #fff2f0;
  color: #ff4d4f;
}

.exam-details {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #86909c;
  font-size: 12px;
}

.card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-header {
  margin-bottom: 24px;
}

.detail-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item label {
  font-weight: 500;
  color: #86909c;
}

.score-highlight {
  color: #165dff;
  font-weight: 600;
}

.detail-chart h4 {
  margin-bottom: 16px;
  color: #1d2129;
}

.chart-container {
  height: 300px;
}

.answers-content {
  max-height: 70vh;
  overflow-y: auto;
}

.question-item {
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.question-number {
  font-weight: 600;
  color: #1d2129;
}

.question-text {
  margin-bottom: 12px;
  line-height: 1.6;
}

.answer-section {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 6px;
}

.answer-item {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
  gap: 8px;
}

.answer-item:last-child {
  margin-bottom: 0;
}

.answer-item label {
  font-weight: 500;
  color: #86909c;
  min-width: 80px;
}

.correct-answer {
  color: #52c41a;
  font-weight: 500;
}

.wrong-answer {
  color: #ff4d4f;
  font-weight: 500;
}

.explanation {
  color: #4e5969;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .records-page {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-stats {
    width: 100%;
    justify-content: space-around;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-controls {
    justify-content: stretch;
  }
  
  .card-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .detail-stats {
    grid-template-columns: 1fr;
  }
}
</style>